import ContractDialog from '@/app/paymentManagement/components/contractDialog';
import RequestNumberDialog from '@/app/paymentManagement/components/requestNumberDialog';
import { getUserInfoA } from '@/basa/api';
import { listUserPartJobComInfo } from '@/app/paymentManagement/paymentApplicationChange/apis';
import { dateFormat1 } from '@/basa/utils';
export default {
  components: {
    ContractDialog,
    RequestNumberDialog,
  },
  watch: {
    // 关闭弹框时重置搜索项
    dialogVisible: {
      handler(item) {
        if (item === false) {
          // 清空搜索项
          this.singleSelectReset();
        }
      },
    },
    formData: {
      handler(newval) {
        this.form = newval;
        // 备份数据
        this.$emit('formCopyDataFun', this.form);
        this.$nextTick(() => {
          console.log('清除提示2');
          this.$refs['basicInfo'].clearValidate();
        });
      },
      deep: true,
    },
    form: {
      handler(newval) {
        // 备份数据
        this.$emit('formCopyDataFun', newval);
      },
      deep: true,
    },
  },
  data() {
    /*本次输入金额的限制*/
    const receivableAmounts = (rule, value, callback) => {
      let str = '';
      if (value) {
        str = value.toString();
      }
      //非空判断
      if (value === null || value === '') {
        return callback(new Error('请输入付款金额'));
      } else {
        setTimeout(() => {
          //限制0 0.0 0.00都不能输入 否则提示 本次收款金额不能输入
          if (str === '0' || str === '0.0' || str === '0.00') {
            callback(new Error('金额不能为' + str));
          }
          //限制-0 -0.0 -0.00都不能输入 否则提示 本次收款金额不能输入
          if (str === '-0' || str === '-0.0' || str === '-0.00') {
            callback(new Error('金额不能为' + str));
          }

          //限制0. -0.都不能输入 否则提示 本次收款金额不能输入
          if (str === '-0.' || str === '0.') {
            callback(new Error('金额不能为' + str));
          }

          // if (str && str.length > 12) {
          //   callback(new Error('金额不能超出12位'));
          // }
          //其他情况正常返回
          callback();
        }, 100);
      }
    };
    return {
      // 填报单位下拉数据
      reportInOrgNameData: [],
      // 付款类型
      paymentTypeData: [
        {
          value: 1,
          label: '预付',
        },
        {
          value: 2,
          label: '应付',
        },
      ],
      paymentModeData: [
        {
          value: 1,
          label: '银行承兑',
        },
        {
          value: 2,
          label: '商业承兑',
        },
        {
          value: 3,
          label: '供应链金融',
        },
        {
          value: 4,
          label: '现金',
        },
      ],
      // 票据月数
      billMonthsData: [
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10,
        11,
        12,
        13,
        14,
        15,
        16,
        17,
        18,
        19,
        20,
        21,
        22,
        23,
        24
      ],
      form: {
        // 提交标识
        optId: '',
        // 变更原因
        changeReason: '',
        // 填报单位名称
        reportInOrgName: '',
        // 填报单位code
        reportInOrgCode: '',
        // 收款人名称（单位名称）
        payee: '',
        // 付款申请单编号
        paymentCode: '',
        // 付款申请单名称
        paymentName: '',
        // 版本号 新增时默认为1，每次修改+1
        version: 1,
        // 合同ID
        contractId: '',
        // 合同编码
        contractCode: '',
        // 合同名称
        contractName: '',
        // 合同含税金额
        initTotalContractPriceIncludeTax: '',
        // 兑人民币汇率
        chExchangeRate: '',
        // 币种名称
        currencyName: '',
        // 币种编码
        currencyCode: '',
        // 已结算金额
        settledPrice: '',
        // 已到票金额
        invoiceIncludeTax: '',
        // 累计已付款
        paymentPrice: '',
        // 应付未付金额
        payablePrice: '',
        // 付款方式 1-银行承兑、2-商业承兑、3-供应链金融、4-现金
        paymentMode: '',
        // 付款类型 1-预付、2-应付
        paymentType: '',
        // 票据月数
        billMonths: '',
        // 付款金额
        paymentMoney: '',
        //  付款日期
        paymentTime: '',
        // 编制日期
        reportTime: '',
        // 编制人
        reportUsername: '',
        // 编制人Id
        reportOpenid: '',
        // 请款事由
        reasons: '',
        // 备注
        remark: '',
        //审批状态 1、草稿   2、待提交  3、审批中  4、审批通过  5、审批不通过 5、审批退回
        approvalStatus: '',
        // 审批时间
        approvalTime: '',
        // 终极版本
        isVersion: '',
        // 创建人（open_id）
        createUserId: '',
        // 创建时间
        createTime: '',
        // 修改人（open_id）
        updateUserId: '',
        // 修改人（名称）
        updateUser: '',
        // 修改时间
        updateTime: '',
        // 是否逻辑删除 1=删除、0=未删除
        isDelete: '',
        // 附件id
        fileList: [],
        /* 登记单新增 */
        // 付款登记编号
        registerCode: '',
        //  付款申请登记名称
        registerName: '',
        // 登记单-付款金额
        registerPrice: '',
        // 登记时间
        registerTime: '',
      },
      rules: {
        registerPrice: [
          { validator: receivableAmounts, trigger: 'blur' },
          { required: true, message: '请输入付款金额' },
        ],
        registerTime: [{ required: true, message: '请选择付款日期' }],
        payee: [{ required: true, message: '请输入收款人' }],
        registerName: [{ required: true, message: '请选择填报单位' }],
        reportInOrgName: [{ required: true, message: '请选择填报单位' }],
        paymentCode: [{ required: true, message: '请输入付款申请单编号' }],
        paymentName: [{ required: true, message: '请输入付款申请单名称' }],
        contractCode: [{ required: true, message: '请选择合同编号' }],
        billMonths: [{ required: true, message: '请选择票据月数' }],
        paymentType: [{ required: true, message: '请选择付款类型' }],
        paymentMode: [{ required: true, message: '请选择付款方式' }],
        paymentMoney: [
          { validator: receivableAmounts, trigger: 'blur' },
          { required: true, message: '请输入付款金额' },
        ],
        paymentTime: [{ required: true, message: '请选择付款日期' }],
        changeReason: [{ required: true, message: '请输入变更原因' }],
      },
      // 供应商高级搜索参数
      singleSelectInput: {
        pageNo: 1,
        pageSize: 20,
      },
      // 合同高级搜索参数
      singleSelectInputContract: {
        pageNo: 1,
        pageSize: 20,
      },
    };
  },
  created() {
    const { status } = JSON.parse(this.$route.params.id);
    this.editStatus = status;
  },

  activated() {
    // 数据初始化
    for (const key in this.form) {
      this.form[key] = '';
    }

    setTimeout(() => {
      // 获取当前登录人openId
      this.getUserInfoFun();

      this.$nextTick(() => {
        console.log('清除提示');
        this.$refs['basicInfo'].clearValidate();
      });
    }, 50);
  },

  computed: {
    // 月票据显示
    isShowBillMonths() {
      return this.form.paymentMode !== 4 && this.form.paymentMode;
    },
    // 付款类型 1-预付、2-应付
    paymentTypeResult() {
      switch (this.form.paymentType) {
        case 1:
          return '预付';
        case 2:
          return '应付';
        default:
          return this.form.paymentType;
      }
    },
  },

  methods: {
    // 基本信息信息接口获取openId
    getUserInfoFun() {
      const _this = this;
      let loadingIstrue;
      if (this.$route.name == "paymentManagement-List-application-detail") {
        loadingIstrue = true
      } else if (this.$route.name == "paymentManagement-List-applicationChange-detail") {
        loadingIstrue = false
      }
      getUserInfoA({ isShowPageLoading: loadingIstrue }).then((res) => {
        // 设置编制人和编制人id
        if (_this.editStatus === 'add') {
          _this.form.reportTime = dateFormat1(new Date().getTime());
          _this.form.reportUsername = res.data.data.userInfo.name;
          _this.form.reportOpenid = res.data.data.userInfo.openId;
        }
        if (_this.editStatus !== 'look')
          _this.listUserPartJobComInfoFun(res.data.data.userInfo.openId);
      });
    },

    // 填报单位下拉数据
    listUserPartJobComInfoFun(openIds) {
      let loadingIstrue1;
      if (this.$route.name == "paymentManagement-List-application-detail") {
        loadingIstrue1 = true
      } else if (this.$route.name == "paymentManagement-List-applicationChange-detail") {
        loadingIstrue1 = false
      }
      listUserPartJobComInfo({ openIds: [openIds], isShowPageLoading: loadingIstrue1 }).then((res) => {
        this.reportInOrgNameData = Object.freeze(res.data.data[openIds]);
        if (this.editStatus === 'add') {
          // 默认选中第一个
          if (
            !this.form.reportInOrgName &&
            this.pageType !== 'registrationForm'
          )
            this.form.reportInOrgName = res.data.data[openIds][0].name;
          if (
            !this.form.reportInOrgCode &&
            this.pageType !== 'registrationForm'
          )
            this.form.reportInOrgCode = res.data.data[openIds][0].orgId;
        }
        // 再次清除校验
        this.$refs['basicInfo'].clearValidate();
      });
    },

    //只能输入数字和两个个小数点 输入金额的限制方法
    formatNumberFixed(name, fixedNum) {
      let numberVal = this.form[name];

      numberVal = numberVal.replace(/[^\d.]/g, '');
      numberVal = numberVal.replace(/\.{2,}/g, '.');
      numberVal = numberVal
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.');

      numberVal = numberVal.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
      if (numberVal.indexOf('.') < 0 && numberVal != '') {
        //首位不能为类似于 01、02的金额
        numberVal = parseFloat(numberVal);
      }
      // 限制整数不超过12位
      numberVal = numberVal.toString();
      if (numberVal.length > 12) {
        if (numberVal.indexOf('.') > -1) {
          numberVal =
            numberVal.split('.')[0].substr(0, 12) +
            '.' +
            numberVal.split('.')[1];
        } else {
          numberVal = numberVal.substr(0, 12);
        }
      }
      this.form[name] = numberVal;
    },

    // 付款方式
    paymentModeDataChange(e) {
      this.form.paymentMode = e;
      if (e === 1 || e === 4) this.form.billMonths = '';
    },
    // 付款类型
    paymentTypeDataChange(e) {
      this.form.paymentType = e;
    },

    // 填报单位
    reportInOrgNameChange(orgId) {
      if (orgId !== this.form.reportInOrgCode) {
        this.form.contractCode = ''
        this.form.contractName = ''
        this.form.initTotalContractPriceIncludeTax = ''
        this.form.currencyName = ''
        this.form.currencyCode = ''
        this.form.chExchangeRate = ''
        this.form.settledPrice = ''
        this.form.invoiceIncludeTax = ''
        this.form.paymentPrice = ''
        this.form.payee = ''
        this.form.contractId = ''
        this.form.payablePrice = ''
      }
      // orgId赋值
      this.form.reportInOrgCode = orgId;
      // 查找对应的name
      this.reportInOrgNameData.map((item) => {
        if (item.orgId === orgId) {
          this.form.reportInOrgName = item.name;
        }
      });
    },

    //票据月数
    billMonthsChange(e) {
      this.form.billMonths = e;
    },

    // 付款申请单编号弹框确定
    confirmTrueRequestNumber(obj) {
      console.log(obj)
      // 除了这些 其他的信息都带出来
      const excludeKeys = [
        'paymentMode',
        'billMonths',
        'registerPrice',
        'paymentTime',
        'reportTime',
        'reportUsername',
        'registerCode',
        'id',
        'registerTime',
      ];
      const includeKeys = [
        'initTotalContractPriceIncludeTax',
        'invoiceIncludeTax',
        'settledPrice',
        'paymentMoney',
      ];

      for (const key in this.form) {
        if (!excludeKeys.includes(key)) {
          if (includeKeys.includes(key)) {
            this.form[key] = Number(obj[key]).toFixed(2) || '0.00';
          } else {
            this.form[key] = obj[key];
          }
        }
      }
    },

    PayablePriceData(data) {
      this.form.payablePrice = Number(data).toFixed(2) || '0.00';
    },

    // 合同弹框确定
    confirmTrue(obj) {
      console.log("222")
      // 为空校验
      if (!obj || Object.keys(obj).length === 0) return;

      const resultObj = {
        // reportInOrgName: '',
        // reportInOrgCode: '',
        contractCode: '',
        contractName: '',
        initTotalContractPriceIncludeTax: '',
        currencyName: '',
        currencyCode: '',
        chExchangeRate: '',
        settledPrice: '',
        invoiceIncludeTax: '',
        paymentPrice: '',
        payee: '',
        contractId: '',
      };
      for (const key in resultObj) {
        if (
          key === 'initTotalContractPriceIncludeTax' ||
          key === 'settledPrice'
        ) {
          this.form[key] = Number(obj[key]).toFixed(2) || '0.00';
        } else if (key === 'contractId') {
          this.form[key] = obj['id'];
        } else {
          this.form[key] = obj[key];
        }
      }
      // 累计已付款
      this.form.paymentPrice = Number(obj.registerPrice).toFixed(2) || '0.00';
      this.form.invoiceIncludeTax = Number(obj.invoiceAmount).toFixed(2) || '0.00';
      this.form.payee = obj.partyBName;
      this.form.partyBExtOid = obj.partyBExtOid;
      this.form.partyBId = obj.partyBId;
      this.form.companyOrgId = obj.companyOrgId;
    },
    // 打开付款申请单弹框
    requestNumberDialogShow() {
      this.$refs.showContractDialog.openContractDialog();
    },
    // 打开合同弹窗
    getContractName(reportOrgId) {
      this.$refs.showContractDialog.openContractDialog(reportOrgId);
    },
    // 
    handleTrim(str) {
      this.form[str] = this.form[str].trim();
      // this.form[str] = this.form[str].replace(/(^\s*)|(\s*)$/g, "");
    },
  },
};
